<template>
    <div class="QrcodeLogin">
        <div class="qrcode-wxgzh" v-if="wxGzhQrcodeShow">
            <img class="login-wxgzh" :src="loginImg"/>
            <div v-if="invalidQrCode" class="code-invalid">
                {{ qrTitle }}，
                <span style="color: #067BEF;cursor: pointer;" @click="getAuthUrl()">刷新</span>
            </div>
        </div>
        <img v-else-if="isLoginError" class="login-img" src="@/image/loading.gif"/>
        <img v-else class="QrcodeLogin-loading" src="@/image/failed.png"/>
        <div :class="[isLoginError?'QrcodeLogin-text-true':'QrcodeLogin-text']">{{titleVal}}</div>
    </div>
</template>

<script>
    import LoginApi from '@/api/login'
    import {
        ACCESS_TOKEN,
        ROOT_TENANT
    } from '@/store/mutation-types'
    import {
        notification
    } from 'ant-design-vue'
    import {
        mapState,
        mapActions,
        mapMutations
    } from 'vuex'
    import store from "@/store";
    /*const DD_ = 'dd';
    const WX_ = 'wx';*/
    import {TokenUtil} from "@lowcode/jpaas-common-lib"
    import {timeFix} from "@/utils/util";

    export default {
        data() {
            return {
                appType: null,
                tenantId: null,
                redirectUrl: "",
                code: null,
                loginType:'',
                isLoginError: true,
                qrTitle:this.i18n('tips.qrInvalid',"二维码已过期"),
                titleVal:this.i18n('tips.getQrcode','正在获取二维码，请稍候...'),
                hostName:"",
                loginImg:"",
                wxGzh:{},
                intervalFun:"",
                wxGzhQrcodeShow:false,
                invalidQrCode:false
            }
        },
        created() {
            this.setLogined(false);
            this.loginType = this.$route.params.loginType;
            if(!this.loginType ){
                this.loginType  = localStorage.getItem("LOGIN_TYPE")?localStorage.getItem("LOGIN_TYPE"):1;
            }else{
                localStorage.setItem("LOGIN_TYPE",this.loginType)
            }
            this.setLoginUrl();
            this.tenantId = this.$route.params.tenantId || this.$route.query.tenantId;
            if (!this.tenantId || this.tenantId.trim().length == 0) {
                this.tenantId = ROOT_TENANT;
            }
            this.hostName = this.$route.params.hostName || this.$route.query.hostName;
            this.code = this.$route.query.code;
            //扫码回调
            if (this.code) {
                this.titleVal=this.i18n('tips.loging','正在进行登录，请稍候...');
                this.autoLoginByCode();
                return;
            }
            this.getAuthUrl();
        },
        computed: {
            ...mapState({
                navigation: state => state.appSetting.navigation,
            })
        },
        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "viewsUser", key);
            },
            ...mapActions({
                AutoLoginByCode: 'user/AutoLoginByCode'
            }),
            ...mapMutations({
                setLogined: 'appSetting/setLogined'
            }),
            //手机验证码登录
            mobileCodeLogin(ticketJson) {
                ticketJson.hostName = this.hostName;
                if(ticketJson.hostName == 'localhost'){
                    ticketJson.hostName="";
                }
                ticketJson.tenantId = this.tenantId;
                this.$router.push({name: 'mobileCodeLogin', query: ticketJson});
            },
            getAuthUrl() {
                this.qrTitle=this.i18n('tips.qrInvalid',"二维码已过期");
                if("1"==this.loginType){
                    this.wxGzh={};
                    this.invalidQrCode=false;
                }
                let params = {
                    tenantId: this.tenantId,
                    redirectUrl: this.redirectUrl,
                    loginType:this.loginType,
                    state:'',
                    paramType:"pc"
                };
                var self_=this;
                LoginApi.getAuthUrl(params).then(res => {
                    if (!res.success || !res.data) {
                        let message=self_.i18n('tips.qrCode','获取二维码失败');
                        self_.isLoginError=false;
                        self_.titleVal=message;
                        self_.errorMsg(message, res.message);
                        return;
                    }
                    if("1"==self_.loginType){
                        self_.setWxGzh(res.data);
                        return;
                    }
                    //跳转到二维码页面
                    window.location.href = res.data;
                }).catch(err => {
                    let message=self_.i18n('tips.qrCode','获取二维码失败');
                    self_.isLoginError=false;
                    self_.titleVal=message;
                    self_.errorMsg(message, JSON.stringify(err));
                })
            },
            setIntervalFun(){
                let start = Date.now();
                let self =this;
                this.intervalFun = setInterval(() => {
                    // 计算已过去的时间
                    let elapsed = Date.now() - start;
                    let num = elapsed / 1000;
                    console.debug("执行定时器时间。。。。。num="+num+"---总时间："+this.wxGzh.expire_seconds);
                    if (num >= this.wxGzh.expire_seconds) {
                        console.debug("停止执行定时器。。。。。");
                        self.invalidQrCode=true;
                        // 清除定时器
                        clearInterval(self.intervalFun);
                        return;
                    }
                    // 每秒执行的操作
                    this.getTokenByTicket();
                }, 1000);
            },
            setWxGzh(wxGzh){
                this.wxGzh=wxGzh;
                let showqrcodeUrl = this.wxGzh.showqrcodeUrl+"?ticket="+this.wxGzh.ticket;
                this.loginImg = showqrcodeUrl;
                this.titleVal=this.i18n('tips.scanWxGzhLogin',"微信扫码关注公众号完成登录");
                this.wxGzhQrcodeShow=true;
                this.setIntervalFun();
            },
            getTokenByTicket() {
                let params = {
                    tenantId: this.tenantId,
                    ticket: this.wxGzh.ticket,
                    sceneId:this.wxGzh.sceneId,
                    hostName:this.hostName
                };
                var self_ = this;
                LoginApi.getTokenByTicket(params).then(res => {
                    console.debug("轮询微信公众是否扫码--结果。。。。。res="+JSON.stringify(res));
                    if(res.isWxGzhNewUser || res.isWxGzhNewUser==true || res.isWxGzhNewUser=="true"){
                        // 清除定时器
                        clearInterval(self_.intervalFun);
                        self_.mobileCodeLogin(res);
                        //跳转到绑定手机验证码登录
                        return;
                    }
                    let token = res.access_token;
                    if(token){
                        // 清除定时器
                        clearInterval(self_.intervalFun);
                        TokenUtil.setToken(token);
                        self_.$store.commit('SET_TOKEN', token);
                        self_.loginWxGzhSuccess();
                    }
                    if(res.loginSuccess=="LOGIN_FAIL"){
                        self_.qrTitle =self_.i18n('tips.failureLogin',"登录失败");
                        self_.invalidQrCode = true;
                        self_.$notification.warning({
                            message: this.i18n('tips.warningTitle',"警告信息"),
                            description: res.failMessage
                        });
                        // 清除定时器
                        clearInterval(self_.intervalFun);
                    }
                })
            },
            //登录成功处理
            loginWxGzhSuccess() {
                this.$router.push({name: 'admin-index'}, () => {
                    this.$notification.success({
                        message: this.i18n('tips.welcome','欢迎'),
                        description: `${timeFix()}，`+this.i18n('tips.welcomeBack','欢迎回来!')
                    })
                })
            },
            //根据code信息尝试自动登录
            autoLoginByCode() {
                //根据Code获取钉钉用户ID
                let params = {
                    tenantId: this.tenantId,
                    code: this.code,
                    loginType:this.loginType
                };
                var self_ = this;
                //用钉钉用户登录系统
                this.AutoLoginByCode(params).then(res2 => {
                    self_.loginSuccess(res2);
                }).catch(err2 => {
                    let message=self_.i18n('tips.failure','自动登录失败');
                    self_.isLoginError=false;
                    self_.titleVal=message;
                    self_.errorMsg(message, JSON.stringify(err2));
                })
            },
            loginSuccess(res) {
                if (!res.success) {
                    let message=this.i18n('tips.failureLogin','登录失败')+":"+this.i18n('tips.application','请先在手机端应用中绑定！');
                    this.isLoginError=false;
                    this.titleVal=message;
                    this.errorMsg(message);
                    return;
                }
                this.$router.push({
                    name: 'home-index'
                }, () => {
                    notification.success({
                        message: this.i18n('tips.welcome','欢迎'),
                        description: this.i18n('tips.back','登录成功，欢迎回来!')
                    })
                });
            },
            errorMsg(title, msg) {
                //出错时消息提醒
                notification.error({
                    message: title,
                    description: msg
                });
                var router = this.$router;
                const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
                wait(5000).then(() => router.push({
                    name: 'login'
                }));
            },
            setLoginUrl(){
                let path = this.$route.path;
                let loginUrl = location.href.split(path)[0] +"/user/qrcodeLogin";
                if(this.tenantId){
                    loginUrl += "?tenantId=" + this.tenantId;
                }
                this.redirectUrl =  loginUrl;
            }
        }
    }
</script>
<style scoped>
.QrcodeLogin{
    display: flex;
    flex-direction: column;
    background: white;
    position: fixed;
    top: 0;
    left: 0px;
    bottom: 0px;
    right: 0px;
    z-index: 9999;
    transform: inherit;
    justify-content: center;
    align-items: center;
}
.login-img{
    width: 700px;
    margin-top: -200px;
}
.QrcodeLogin-loading{
    width: 400px;
    margin-top: -200px;
}
.QrcodeLogin-text-true{
    text-align: center;
    color: #333333;
    font-size: 20px;
}
.QrcodeLogin-text{
    text-align: center;
    color: #333333;
    font-size: 20px;
}
.qrcode-wxgzh{
    width: 200px;
    height: 200px;
    background: #fff;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid #e9edf2;
    margin: 0 auto 30px;
    position: relative;
    overflow: hidden;
}
.login-wxgzh{
    width: 100%;
    height: 100%;
}
.code-invalid{
    width: 200px;
    height: 200px;
    line-height: 200px;
    background: rgba(255, 255, 255, 0.95);
    position: absolute;
    text-align: center;
    top: 0;
    left: 0;
}
</style>
